package com.atguigu.lease.common.utils;

import ch.qos.logback.classic.spi.EventArgUtil;
import com.atguigu.lease.common.Exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;

public class JwtUtil {

    private static Long tokenExpiration = 60 * 60 * 1000L;
    private static SecretKey KEY = Keys.hmacShaKeyFor("QBwqeRQriNMfcNgNiKSbkmKwbIvUVBuZ".getBytes());

//    public static String generateJwt(String username, Long userId) {
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("userName", username);
//        map.put("userId", userId);
//        return Jwts.builder()
////                设置过期时间
//                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
////                设置jwt主体
//                .setSubject("LOGIN_JWT")
////                jwt携带的信息
//                .addClaims(map)
//                .signWith(KEY, SignatureAlgorithm.HS256).compact();
//    }

    public static String generateJwt(String phone, Long userId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("phone", phone);
        return Jwts.builder()
                /*设置过期时间*/
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                /*设置jwt主体*/
                .setSubject("LOGIN_JWT")
                /*jwt携带的信息*/
                .addClaims(map)
                .signWith(KEY, SignatureAlgorithm.HS256).compact();
    }

    public static Claims parseJwt(String jwt) {
        if (jwt == null) throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        try {
            Claims body = Jwts.parserBuilder()
                    .setSigningKey(KEY)
                    .build()
                    .parseClaimsJws(jwt).getBody();
            return body;
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }

    public static void main(String[] args) {
        System.out.println(generateJwt("18718477470", 10L));
    }


}
